package com.tiancai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiancai.context.BaseContext;
import com.tiancai.pojo.dto.WorkDto;
import com.tiancai.pojo.po.*;
import com.tiancai.pojo.vo.CommentVo;
import com.tiancai.pojo.vo.UserWorkPowerVo;
import com.tiancai.pojo.vo.WorkDetailVo;
import com.tiancai.result.PageResult;
import com.tiancai.result.Result;
import com.tiancai.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tiancai
 * @since 2025-03-09
 */
@RestController
@RequestMapping("/work")
@Tag(name = "作品管理")
@CrossOrigin
@Slf4j
public class WorkController {
    @Autowired
    private IWorkService workService;

    @Autowired
    private IUserViewWorkService userViewWorkService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICollectService collectService;

    @Autowired
    private IWorkRentService workRentService;

    @Autowired
    private IUserCommentLikeService userCommentLikeService;



    // 新增作品
    @PostMapping("/add")
    @Operation(summary = "新增作品")
    public Result<Work> add(@RequestBody WorkDto workDto) {
        Work work = new Work();
        // code设置为UUID
        work.setCode(UUID.randomUUID().toString());
        BeanUtils.copyProperties(workDto, work);
        work.setUserId(BaseContext.getCurrentId());
        work.setOrginUserId(BaseContext.getCurrentId());
        workService.save(work);
        // 作者的上传作品数加一
        User user = userService.getById(BaseContext.getCurrentId());
        user.setUploadCount(user.getUploadCount() + 1);
        // 作者的拥有作品数加一
        user.setOwnCount(user.getOwnCount() + 1);
        return Result.success(work);
    }

    @GetMapping("/getById/{id}")
    @Operation(summary = "根据id查询作品详情")
    public Result<WorkDetailVo> getById(@PathVariable Long id) {
        Work work = workService.getById(id);
        WorkDetailVo workDetailVo = new WorkDetailVo();
        BeanUtils.copyProperties(work, workDetailVo);
        // 根据用户id查看收藏表看当前用户是否收藏作品
        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Collect::getUserId, BaseContext.getCurrentId()).eq(Collect::getWorkId, id);
        // 查看收藏表
        if (collectService.getOne(wrapper) != null) {
            workDetailVo.setIsCollect(true);
        } else {
            workDetailVo.setIsCollect(false);
        }
        return Result.success(workDetailVo);
    }

    @PutMapping("/update")
    @Operation(summary = "更新作品")
    public Result<Work> update(@RequestBody WorkDto workDto) {
        Work work = workService.getById(workDto.getId());
        BeanUtils.copyProperties(workDto, work);
        workService.updateById(work);
        return Result.success(work);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除作品")
    public Result<Work> delete(Long id) {
        Work work = workService.getById(id);
        if (!work.getUserId().equals(BaseContext.getCurrentId())) return Result.error("无权限");
        workService.removeById(id);
        return Result.success();
    }


    @GetMapping("/search")
    @Operation(summary = "综合搜索：根据title、type、status、userId筛选，按收藏数、浏览数、创建时间排序，分页查询")
    @Parameters({@Parameter(name = "title", description = "作品标题关键字"), @Parameter(name = "categoryId", description = "作品分类id"), @Parameter(name = "status", description = "作品状态"), @Parameter(name = "userId", description = "用户ID"), @Parameter(name = "sortBy", description = "排序字段：collectCount/viewCount/createTime，默认createTime"), @Parameter(name = "currPage", description = "页码，默认1"), @Parameter(name = "pageSize", description = "每页数量，默认10")})
    public Result<PageResult> search(@RequestParam(required = false) String title,
                                     @RequestParam(required = false) Long categoryId,
                                     @RequestParam(required = false) Integer status,
                                     @RequestParam(required = false) Long userId,
                                     @RequestParam(defaultValue = "createTime") String sortBy,
                                     @RequestParam(defaultValue = "1") int currPage,
                                     @RequestParam(defaultValue = "10") int pageSize) {

        QueryWrapper<Work> wrapper = new QueryWrapper<>();

        // 条件筛选
        if (StringUtils.isNotEmpty(title)) {
            wrapper.lambda().like(Work::getTitle, title);
        }
        if (categoryId != null) {
            wrapper.lambda().eq(Work::getCategoryId, categoryId);
        }
        if (status != null) {
            wrapper.lambda().eq(Work::getStatus, status);
        }
        if (userId != null) {
            wrapper.lambda().eq(Work::getUserId, userId);
        }

        // 排序逻辑
        switch (sortBy.toLowerCase()) {
            case "collectcount":
                wrapper.lambda().orderByDesc(Work::getCollectCount);
                break;
            case "viewcount":
                wrapper.lambda().orderByDesc(Work::getViewCount);
                break;
            default:
                wrapper.lambda().orderByDesc(Work::getCreateTime);
        }

        // 分页查询
        Page<Work> pageInfo = new Page<>(currPage, pageSize);
        Page<Work> workPage = workService.page(pageInfo, wrapper);
        return Result.success(new PageResult(workPage.getTotal(), workPage.getRecords()));
    }
    // @GetMapping("/search11")
    // @Operation(summary = "综合搜索：根据title、type、status、userId筛选，按收藏数、浏览数、创建时间排序，分页查询")
    // @Parameters({
    //         @Parameter(name = "title", description = "作品标题关键字"),
    //         @Parameter(name = "categoryId", description = "作品分类id"),
    //         @Parameter(name = "status", description = "作品状态"),
    //         @Parameter(name = "userId", description = "用户ID"),
    //         @Parameter(name = "sortBy", description = "排序字段：collectCount/viewCount/createTime，默认createTime"),
    //         @Parameter(name = "currPage", description = "页码，默认1"),
    //         @Parameter(name = "pageSize", description = "每页数量，默认10")
    // })
    // public Result<PageResult<WorkDetailVo>> search(
    //         @RequestParam(required = false) String title,
    //         @RequestParam(required = false) Long categoryId,
    //         @RequestParam(required = false) Integer status,
    //         @RequestParam(required = false) Long userId,
    //         @RequestParam(defaultValue = "createTime") String sortBy,
    //         @RequestParam(defaultValue = "1") int currPage,
    //         @RequestParam(defaultValue = "10") int pageSize) {
    //
    //     QueryWrapper<Work> wrapper = new QueryWrapper<>();
    //
    //     // 条件筛选
    //     if (StringUtils.isNotEmpty(title)) {
    //         wrapper.lambda().like(Work::getTitle, title);
    //     }
    //     if (categoryId != null) {
    //         wrapper.lambda().eq(Work::getCategoryId, categoryId);
    //     }
    //     if (status != null) {
    //         wrapper.lambda().eq(Work::getStatus, status);
    //     }
    //     if (userId != null) {
    //         wrapper.lambda().eq(Work::getUserId, userId);
    //     }
    //
    //     // 排序逻辑
    //     switch (sortBy.toLowerCase()) {
    //         case "collectcount":
    //             wrapper.lambda().orderByDesc(Work::getCollectCount);
    //             break;
    //         case "viewcount":
    //             wrapper.lambda().orderByDesc(Work::getViewCount);
    //             break;
    //         default:
    //             wrapper.lambda().orderByDesc(Work::getCreateTime);
    //     }
    //
    //     // 分页查询
    //     Page<Work> pageInfo = new Page<>(currPage, pageSize);
    //     Page<Work> workPage = workService.page(pageInfo, wrapper);
    //
    //     // 将 Work 转换为 WorkDetailVo
    //     List<WorkDetailVo> workDetailVos = workPage.getRecords().stream()
    //             .map(work -> {
    //                 WorkDetailVo workDetailVo = new WorkDetailVo();
    //                 BeanUtils.copyProperties(work, workDetailVo);
    //                 // 根据用户id查看收藏表看当前用户是否收藏作品
    //                 QueryWrapper<Collect> collectWrapper = new QueryWrapper<>();
    //                 collectWrapper.lambda()
    //                         .eq(Collect::getUserId, BaseContext.getCurrentId())
    //                         .eq(Collect::getWorkId, work.getId());
    //                 workDetailVo.setIsCollect(collectService.getOne(collectWrapper) != null);
    //                 return workDetailVo;
    //             })
    //             .collect(Collectors.toList());
    //
    //     // 封装分页结果
    //     Page<WorkDetailVo> resultPage = new Page<>(currPage, pageSize);
    //     resultPage.setRecords(workDetailVos);
    //     resultPage.setTotal(workPage.getTotal());
    //
    //     return Result.success(new PageResult<>(resultPage.getTotal(), resultPage.getRecords()));
    // }

    @PostMapping("/isView")
    @Operation(summary = "查看用户是否浏览过这个作品")
    public Result isView(Long workId) {
        QueryWrapper<UserViewWork> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserViewWork::getUserId, BaseContext.getCurrentId()).eq(UserViewWork::getWorkId, workId);
        UserViewWork userViewWork = userViewWorkService.getOne(wrapper);
        if (userViewWork == null) {
            UserViewWork userViewWork1 = UserViewWork.builder().userId(BaseContext.getCurrentId()).workId(workId).isview(1).build();
            userViewWorkService.save(userViewWork1);
            // 作品浏览量加一
            QueryWrapper<Work> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Work::getId, workId);
            Work work = workService.getOne(queryWrapper);
            work.setViewCount(work.getViewCount() + 1);
            workService.updateById(work);
        }
        if (userViewWork != null) return Result.success(userViewWork);
        return Result.success();
    }


    // 根据作品id查看所有的评论
    @GetMapping("/getCommentByWorkId")
    @Operation(summary = "根据作品id查看所有的评论")
    public Result<List<CommentVo>> getCommentByWorkId(Long workId) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Comment::getWorkId, workId);
        List<Comment> commentList = commentService.list(wrapper);
        List<CommentVo> commentVoList = new ArrayList<>();
        //便利所有评论查看是否被点赞
        for (Comment comment : commentList) {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(comment, commentVo);
            QueryWrapper<UserCommentLike> wrapper1 = new QueryWrapper<>();
            wrapper1.lambda()
                    .eq(UserCommentLike::getCommentId, comment.getId())
                    .eq(UserCommentLike::getUserId, BaseContext.getCurrentId());
            if (userCommentLikeService.getOne(wrapper1) != null) {
                commentVo.setLiked(true);
            } else {
                commentVo.setLiked(false);
            }
            commentVoList.add(commentVo);
        }
        return Result.success(commentVoList);
    }

    // 根据作品id查询作者id
    @GetMapping("/getUserIdByWorkId")
    @Operation(summary = "根据作品id查询作者")
    public Result<User> getUserIdByWorkId(Long workId) {
        QueryWrapper<Work> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Work::getId, workId);
        Work work = workService.getOne(wrapper);
        return Result.success(userService.getById(work.getUserId()));
    }

    //作品权限查询，就是看某个用户有某个作品的什么权利。根据传来的用户的code与作品的code

    public UserWorkPowerVo getWorkPower(String userCode, String workCode) {
        //根据作品code查询作品
        QueryWrapper<Work> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Work::getCode, workCode);
        Work work = workService.getOne(wrapper);
        //根据userCode查询用户
        QueryWrapper<User> wrapperUser = new QueryWrapper<>();
        wrapperUser.lambda().eq(User::getCode, userCode);
        User user = userService.getOne(wrapperUser);
        UserWorkPowerVo userWorkPowerVo = new UserWorkPowerVo();
        //查看作者id与用户id是否相同，相同则返回true，否则返回false
        if (work.getUserId().equals(user.getId())) {
            userWorkPowerVo.setAuthor(true);
            userWorkPowerVo.setHasUsageRight(true);
        } else {
            //根据用户id与作品id查询作品租赁表
            QueryWrapper<WorkRent> wrapperWorkUse = new QueryWrapper<>();
            wrapperWorkUse.lambda()
                    .eq(WorkRent::getUserId, user.getId())
                    .eq(WorkRent::getWorkId, work.getId());
            WorkRent workRent = workRentService.getOne(wrapperWorkUse);
            if (workRent != null) {
                userWorkPowerVo.setAuthor(false);
                userWorkPowerVo.setHasUsageRight(true);
            } else {
                userWorkPowerVo.setAuthor(false);
                userWorkPowerVo.setHasUsageRight(false);
            }
        }
        userWorkPowerVo.setUserId(user.getId());
        userWorkPowerVo.setUserName(user.getUsername());
        return userWorkPowerVo;
    }

    //根据用户code列表与作品code查询作品使用权列表并返回
    @PostMapping("/getWorkPowerList")
    @Operation(summary = "根据列表查询对应作品权限")
    public Result<List<UserWorkPowerVo>> getWorkPowerList(
            @RequestBody List<String> userCodeList,
            @RequestParam String workCode) {
        log.info("userCodeList:{}", userCodeList);
        log.info("workCode:{}", workCode);
        List<UserWorkPowerVo> userWorkPowerVoList = new ArrayList<>();
        for (String userCode : userCodeList) {
            UserWorkPowerVo userWorkPowerVo = getWorkPower(userCode, workCode);
            userWorkPowerVoList.add(userWorkPowerVo);
        }
        return Result.success(userWorkPowerVoList);
    }
}
